import 'dart:io';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';

// import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/routers/path_location.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:rabbit_mobile/theme/index.dart';

void main(List<String> args) async {
  // debugPaintSizeEnabled = true; // 启用布局边界调试
  WidgetsFlutterBinding.ensureInitialized();
  LocaleSettings.useDeviceLocale();
  if (kIsWeb) {
    // Web 不需要配置状态栏，直接返回
    debugPrint('This is web platform');
  } else {
    try {
      // 程序启动后, 一次性设置状态栏的颜色，仅适用于非 Web 平台
      if (Platform.isAndroid) {
        SystemChrome.setSystemUIOverlayStyle(
          const SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
            statusBarIconBrightness: Brightness.light, // 状态栏图标颜色
          ),
        );
      } else if (Platform.isIOS) {
        SystemChrome.setSystemUIOverlayStyle(
          const SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
            statusBarIconBrightness: Brightness.dark, // 状态栏图标颜色
          ),
        );
      }
    } catch (e) {
      // 捕获可能的异常，避免崩溃
      debugPrint('Error configuring status bar: $e');
    }
  }
  runApp(TranslationProvider(child: const ProviderScope(child: MyApp())));
}

class MyApp extends ConsumerStatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends ConsumerState<MyApp> {
  late final BeamerDelegate _beamerDelegate;

  @override
  void initState() {
    super.initState();
    // _loadAndSetLocale();
    _beamerDelegate = BeamerDelegate(
      locationBuilder: BeamerLocationBuilder(
        beamLocations: [PathLocation()],
      ),
      notFoundRedirectNamed: '/home',
    );
  }

  // 加载并设置语言
  // void _loadAndSetLocale() async {
  //   String storedLocale = await loadFromStorage(); // 从存储中加载语言
  //   LocaleSettings.setLocaleRaw(storedLocale); // 设置语言
  // }

  // 从存储中读取保存的语言设置
  Future<String> loadFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    String? storedLocale = prefs.getString('locale'); // 获取已存储的语言
    return storedLocale ?? 'de'; // 默认是英语
  }

  @override
  Widget build(BuildContext context) {
    final themeMode = ref.watch(themeModeProvider);
    Locale convertAppLocaleToLocale(AppLocale appLocale) {
      switch (appLocale) {
        case AppLocale.de:
          return const Locale('de', '');
        case AppLocale.en:
          return const Locale('en', '');
        case AppLocale.zhHans:
          return const Locale('zh', 'Hans');
        case AppLocale.zhHant:
          return const Locale('zh', 'Hant');
        default:
          return const Locale('en');
      }
    }

    return MaterialApp.router(
      builder: EasyLoading.init(),
      debugShowCheckedModeBanner: false,
      themeMode: themeMode,
      theme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          brightness: Brightness.light,
        ),
      ),
      darkTheme: ThemeData(
        useMaterial3: true,
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          brightness: Brightness.dark,
        ),
      ),
      routerDelegate: _beamerDelegate,
      routeInformationParser: BeamerParser(),
      backButtonDispatcher: BeamerBackButtonDispatcher(delegate: _beamerDelegate),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate
      ],
      supportedLocales: AppLocale.values.map((locale) => convertAppLocaleToLocale(locale)).toList(),
      locale: convertAppLocaleToLocale(ref.watch(translationProvider)),
    );
  }
}
